#!python3
# -*- coding: utf-8 -*-
# works on windows XP, 7, 8, 8.1 and 10
import os
import sys
import time
import subprocess
import unittest
from HTMLTestRunner1 import HTMLTestRunner

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))  # not required after 'pip install uiautomation'
import uiautomation as auto
from sendemail.send_email import SendEmail

auto.uiautomation.DEBUG_EXIST_DISAPPEAR = True  # set it to False and try again, default is False
auto.uiautomation.DEBUG_SEARCH_TIME = True  # set it to False and try again, default is False
auto.uiautomation.TIME_OUT_SECOND = 7  # global time out
print('timeout: {}, old {} is not effective'.format(auto.uiautomation.TIME_OUT_SECOND, auto.TIME_OUT_SECOND))
auto.uiautomation.SetGlobalSearchTimeout(6)  # global time out
print('timeout: {}, old {} is not effective'.format(auto.uiautomation.TIME_OUT_SECOND, auto.TIME_OUT_SECOND))

global_process = {}
class MyTestCase1(unittest.TestCase):
    def setUp(self):
        auto.Logger.WriteLine("启动Case", auto.ConsoleColor.Cyan, writeToFile=False)
    def test_case001(self):
        self.assertFalse(DeleteProject())
    def test_case002(self):
        self.assertTrue(NewProject())
    def test_case003(self):
        self.assertTrue(EnterParameterSettingsWidget())
    def tearDown(self):
        auto.Logger.WriteLine("结束Case", auto.ConsoleColor.Cyan, writeToFile=False)

def getImage(window, imgPath):
    timestrmap = time.strftime('%Y%m%d_%H.%M.%S')
    imgPath = os.path.join(imgPath, '%s.png' % str(timestrmap))
    window.CaptureToImage(imgPath, 7, 0, -14, -7)
    print('screenshot:', timestrmap, '.png')

def delete_files(folder_path):
    files = os.listdir(folder_path)
    for file in files:
        file_path = os.path.join(folder_path, file)
        if os.path.isfile(file_path):
            os.remove(file_path)

def DeleteProject():
    delete_files("./report/images")
    displayMarkWindow = auto.WindowControl(searchDepth=1, ClassName='ScreenMeasureToolsNS::MainWindow',
                                           Name='DisplayMark')
    global global_process
    if not displayMarkWindow.Exists(0, 0):
        global_process = subprocess.Popen('C:/Program Files (x86)/Nova Star/Display Mark/Bin/DisplayMark.exe')
    time.sleep(3)
    displayMarkWindow.SetActive()
    projectCardView = displayMarkWindow.ListControl(ClassName='ProjectCardView')
    item = projectCardView.ListItemControl(Name='按钮')
    if item.Exists(0, 0):
        auto.Click(item.BoundingRectangle.left + 270, item.BoundingRectangle.top + 24)
        modelDialog = displayMarkWindow.WindowControl(ClassName='ModelDialogUI')
        modelDialog.ButtonControl(ClassName='PushButtonEx', Name='确定').Click()
    time.sleep(0.5)
    return projectCardView.ListItemControl(Name='按钮').Exists()

def NewProject():
    displayMarkWindow = auto.WindowControl(searchDepth=1, ClassName='ScreenMeasureToolsNS::MainWindow',
                                           Name='DisplayMark')
    displayMarkWindow.SetActive()
    displayMarkWindow.ButtonControl(ClassName='NStyleButton', Name='新建工程').Click()
    time.sleep(0.5)
    projectCreateDialog = displayMarkWindow.WindowControl(searchDepth=1, ClassName='ProjectCreateDialog')
    nameEdit = projectCreateDialog.EditControl(ClassName='NLineDialogEdit')
    nameEdit.GetValuePattern().SetValue('按钮')
    time.sleep(0.5)
    projectCreateDialog.ButtonControl(ClassName='NStyleButton', Name='确定').Click()
    time.sleep(0.5)
    topNavigationBar = displayMarkWindow.CustomControl(ClassName='TopNavigationBar')
    topNavigationBar.ButtonControl(ClassName='NStyleButton', Name='返回首页 ').Click()
    time.sleep(0.2)
    modelDialog = displayMarkWindow.WindowControl(ClassName='ModelDialogUI')
    modelDialog.ButtonControl(ClassName='PushButtonEx', Name='确定').Click()
    time.sleep(0.2)
    path = "./report/images"
    getImage(displayMarkWindow, path)
    projectCardView = displayMarkWindow.ListControl(ClassName='ProjectCardView')
    item = projectCardView.ListItemControl(Name='按钮')
    isok = item.Exists(0, 0)
    return isok

def EnterParameterSettingsWidget():
    displayMarkWindow = auto.WindowControl(searchDepth=1, ClassName='ScreenMeasureToolsNS::MainWindow', Name='DisplayMark')
    displayMarkWindow.SetActive()
    projectCardView = displayMarkWindow.ListControl(ClassName='ProjectCardView')
    item = projectCardView.ListItemControl(Name='按钮')
    print(item.GetValuePattern().Value)
    item.DoubleClick()
    time.sleep(2)
    label = displayMarkWindow.TextControl(ClassName='NClickLabel', Name='控制器')
    time.sleep(2)
    isOk = label.Exists(0, 0)
    global_process.kill()
    return isOk


if __name__ == '__main__':
    # 1.测试用例集合1
    suite1 = unittest.TestLoader().loadTestsFromTestCase(MyTestCase1)
    # 2.加载所有的被测试对象：将所有的测试用例集合，加在一起
    suite = unittest.TestSuite([suite1])

    report_path = "./report/reportDemo.html"
    f = open(report_path, 'wb')
    runner = HTMLTestRunner(stream=f,
                                title='自动化测试报告',
                                description='generated by HTMLTestRunner.',
                                verbosity=2,
                                tester='helei'
                            )
    result = runner.run(suite)
    f.close()
    status = []
    status.append('共 %s 个用例' % (result.success_count + result.failure_count + result.error_count))
    status.append('通过的测试用例数: %s' % result.success_count)
    status.append('失败的测试用例数: %s' % result.failure_count)
    status.append('错误的测试用例数: %s' % result.error_count)
    HTML_TMPL = r"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>自动化测试报告</title>
    </head>
    <body>
        <h1>自动化测试报告</h1>
        <h2>测试结果：</h2>
        <p>%(total)s</p>
        <p>%(success)s</p>
        <p>%(failure)s</p>
        <p>%(error)s</p>
        <h2>详情见附件！！！</h2>
    </body>
    </html>
    """
    body = ""
    if status:
        body = HTML_TMPL % dict(
            total=status[0],
            success=status[1],
            failure=status[2],
            error=status[3],
        )
    title = time.strftime("%Y-%m-%d", time.localtime()) + "自动化测试"
    email = SendEmail(title, body, "html", "./report")
    email.send()


